package com.cy.api;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicLong;

public class ThreadPoolExecutorTests {
    //创建任务队列，存储待执行的任务
    static BlockingQueue<Runnable> workQueue=
            new ArrayBlockingQueue<>(1);
    //构建线程工厂
    static ThreadFactory threadFactory=new ThreadFactory() {
        //线程名前缀
        private String prefix="pool-thread-task-";
        //定义一个提供了自增自减机制的对象
        private AtomicLong atomicLong=new AtomicLong(1);
        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r,prefix+atomicLong.getAndIncrement());
        }
    };

    public static void main(String[] args) {
        //初始化一个线程池
        ThreadPoolExecutor tPool=
                new ThreadPoolExecutor(1,
                        2,
                        3,
                        TimeUnit.SECONDS,
                        workQueue,
                        threadFactory,
                        new ThreadPoolExecutor.CallerRunsPolicy());
        tPool.execute(new Runnable() {
            @Override
            public void run() {
               String task=Thread.currentThread().getName()+"->task01";
               System.out.println(task);
               try{Thread.sleep(3000);}catch (Exception e){}
            }
        });
        tPool.execute(new Runnable() {
            @Override
            public void run() {
                String task=Thread.currentThread().getName()+"->task02";
                System.out.println(task);
                try{Thread.sleep(3000);}catch (Exception e){}
            }
        });
        tPool.execute(new Runnable() {
            @Override
            public void run() {
                String task=Thread.currentThread().getName()+"->task03";
                System.out.println(task);
                try{Thread.sleep(3000);}catch (Exception e){}
            }
        });
        tPool.execute(new Runnable() {
            @Override
            public void run() {
                String task=Thread.currentThread().getName()+"->task04";
                System.out.println(task);
                try{Thread.sleep(3000);}catch (Exception e){}
            }
        });
    }
}
